<template>
  <div class="app-container">
    <el-dialog
      title="发送消息"
      :visible.sync="messageDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="messageForm" :model="messageForm" label-width="100px">
        <el-form-item label="考试名称" prop="title">
          {{ messageForm.title }}
        </el-form-item>
        <el-form-item label="消息类别" prop="messageType">
          <b v-if="theState!==3">考试提醒</b>
          <b v-else>成绩通知</b>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="messageLoading" @click="sendMessage">发送</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <Edit :infoid="id" :read-only="readonly" :timestamp="timestamp" @dialogHide="dialogHide($event)" />
    </el-dialog>
    <el-dialog
      :title="userDialogtitle"
      :visible.sync="userDialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <Users :infoid="id" :read-only="readonly" :timestamp="timestamp" @dialogHide="userDialogHide($event)" />
    </el-dialog>

    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入关键词" style="width: 200px;margin-left: 10px;" class="filter-item" />
      <el-select v-model="listQuery.state" placeholder="请选择状态" clearable style="margin-left: 10px;width: 120px" class="filter-item">
        <el-option label="全部" :value="null" />
        <el-option label="未开始" :value="0" />
        <el-option label="进行中" :value="1" />
        <el-option label="已结束" :value="2" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilter">
        搜索
      </el-button>
      <el-popconfirm title="确定批量删除所选信息吗？" style="margin-left:10px;float:right" @onConfirm="deleteData()">
        <el-button slot="reference" type="danger" class="filter-item" icon="el-icon-delete">批量删除</el-button>
      </el-popconfirm>
      <el-button class="filter-item" style="margin-left: 10px;float:right" type="success" icon="el-icon-edit" @click="addnew">
        新建
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%" @sort-change="sortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />

      <el-table-column align="center" prop="id" label="编号" width="80" sortable="custom">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" prop="title" label="考试名称" sortable="custom" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>

      <el-table-column width="120px" prop="begin_time" align="center" label="开始日期" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.beginTime }}
        </template>
      </el-table-column>
      <el-table-column width="120px" prop="end_time" align="center" label="结束日期" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.endTime }}
        </template>
      </el-table-column>

      <el-table-column label="人数" prop="usersCount" width="160" align="center">
        <template slot-scope="scope">
          共<b>{{ scope.row.usersCount }}</b>人<template v-if="scope.row.extraUsersCount">（额外<b>{{ scope.row.extraUsersCount }}</b>人）</template>
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="examState" width="100" align="center">
        <template slot-scope="scope">
          {{ id2State(scope.row.examState) }}
        </template>
      </el-table-column>

      <el-table-column label="发布" prop="published" width="90" align="center" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.published" type="success" effect="dark" style="cursor:pointer" title="取消发布此信息" @click="publish(scope.row.id,false,scope.row.title)">已发布</el-tag>
          <el-tag v-else type="info" effect="dark" style="cursor:pointer" title="发布此信息" @click="publish(scope.row.id,true,scope.row.title)">未发布</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="600">
        <template slot-scope="scope">
          <el-button size="small" type="primary" icon="el-icon-edit" style="float:left" @click="detail(scope.row.id)">
            编辑
          </el-button>
          <el-button size="small" type="warning" icon="el-icon-user" style="float:left" @click="users(scope.row.id)">
            人员
          </el-button>
          <el-button size="small" icon="el-icon-download" style="float:left" @click="exportUsers(scope.row.id)">
            导出
          </el-button>

          <el-upload
            v-if="scope.row.examState===3"
            class="upload-demo"
            :action="$http.defaults.baseURL+'api/busExamination/saveImport?id='+scope.row.id"
            :on-success="handleUploadSucc"
            :on-error="uploadError"
            :headers="myHeaders"
            :show-file-list="false"
            style="display:block;float:left;margin-left:10px;"
          >
            <el-button
              type="success"
              class="filter-item"
              icon="el-icon-upload2"
              size="small"
              style="float:left"
            >导入</el-button>
          </el-upload>

          <el-tooltip v-else class="item" effect="dark" content="考试结束后才能导入成绩" placement="top">
            <div style="float:left;margin-left:10px;">
              <el-button
                type="success"
                class="filter-item"
                icon="el-icon-upload2"
                size="small"
                style="float:left"
                :disabled="true"
              >导入</el-button>
            </div>
          </el-tooltip>
          <el-button v-if="scope.row.published" size="small" type="primary" icon="el-icon-message" style="float:left;margin-left:10px;" @click="message(scope.row.id,scope.row.title,scope.row.examState)">
            消息
          </el-button>

          <el-tooltip v-else class="item" effect="dark" content="发布后才能发送消息" placement="top">
            <div style="float:left;">
              <el-button :disabled="true" size="small" type="primary" icon="el-icon-message" style="float:left;margin-left:10px;" @click="message(scope.row.id,scope.row.title,scope.row.examState)">
                消息
              </el-button>
            </div>
          </el-tooltip>
          <el-popconfirm title="确定删除该信息吗？" style="margin-left:10px;float:left" @onConfirm="deleteData(scope.row.id)">
            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
// import { fetchList } from '@/api/article'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Edit from './components/ArticleDetail'
import Users from './components/users'

export default {
  name: 'ArticleList',
  components: { Pagination, Edit, Users },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      rolePublisher: true,
      theState: '',
      messageDialogVisible: false,
      messageForm: {
        examId: '',
        title: '',
        messageType: 1
      },
      messageLoading: false,
      myHeaders: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      userDialogtitle: '',
      userDialogVisible: false,
      dicListLoading: false,
      stopDicLoading: false,
      startDicLoading: false,
      submitLoading: false,
      classList: [],
      classForm: {
        parentClass: 14,
        label: ''
      },
      diclist: [],
      settingVisible: false,
      item: {},
      dialogtitle: '新增',
      dialogVisible: false,
      readonly: false,
      timestamp: false,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        title: '',
        state: null
      },
      Sortkey: '',
      Isace: '',
      multipleSelection: [],
      id: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    publish(id, state, title) {
      if (this.rolePublisher && !this.selection) {
        const stateText = state ? ' 发布 ' : ' 取消发布 '
        this.$confirm('确定要' + stateText + '考试《' + title + '》吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http
            .post('/api/busExamination/saveExamination', { id: id, published: state })
            .then(response => {
              if (response.data.success === true) {
                this.$message({
                  message: stateText + '成功',
                  type: 'success'
                })
                this.getList()
              } else {
                console.log(stateText + '失败:' + response.data.message)
                this.$message({
                  message: stateText + '失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已放弃' + stateText + '操作'
          })
        })
      }
    },
    sendMessage() {
      let message = ''
      if (this.messageForm.messageType === 1) {
        message = '您确定要给考试《' + this.messageForm.title + '》的参与人员发送考试提醒吗？'
      } else if (this.messageForm.messageType === 2) {
        message = '您确定要给考试《' + this.messageForm.title + '》的参与人员发送成绩通知吗？'
      }
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const para = {
          examId: this.messageForm.examId,
          messageType: this.messageForm.messageType
        }
        this.messageLoading = true
        this.$http
          .post('/api/busExamination/sendExaminationMessage', para)
          .then(response => {
            this.messageLoading = false
            if (response.data.success === true) {
              this.$message({
                message: '发送成功',
                type: 'success'
              })
              this.messageDialogVisible = false
              this.getList()
            } else {
              console.log('发送失败:' + response.data.message)
              this.$message({
                message: '发送失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            this.messageLoading = false
            console.log(error)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    message(id, title, state) {
      this.messageForm.examId = id
      this.messageForm.title = title
      this.messageDialogVisible = true
      this.theState = state
      if (state === 3) {
        this.messageForm.messageType = 2
      } else {
        this.messageForm.messageType = 1
      }
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '导入失败:' + err,
        type: 'error',
        duration: 10000
      })
    },
    handleUploadSucc(response, file, fileList) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '导入成功!'
        })
        this.getList()
      } else {
        this.$message({
          message: '导入失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    exportUsers(id) {
      window.open(this.$http.defaults.baseURL + 'api/busExamination/getExport?id=' + id)
    },
    id2State(id) {
      switch (id) {
        case 1:
          return '未开始'
        case 2:
          return '进行中'
        case 3:
          return '已结束'
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteData(id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      if (ids.length > 0) {
        this.$http
          .post('/api/busExamination/removeExamination', { idList: ids })
          .then(response => {
            if (response.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getList()
            } else {
              console.log('删除失败:' + response.data.message)
              this.$message({
                message: '删除失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    addnew() {
      this.id = 0
      this.readonly = false
      this.dialogtitle = '新增'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    detail(id) {
      this.id = id
      this.readonly = true
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    users(id) {
      this.id = id
      this.readonly = true
      this.userDialogtitle = '人员'
      this.userDialogVisible = true
      this.timestamp = new Date().getTime()
    },
    dialogHide(flag) {
      this.dialogVisible = false
      this.getList()
    },
    userDialogHide(flag) {
      this.userDialogVisible = false
      this.getList()
    },
    getList() {
      const para = {
        state: this.listQuery.state,
        title: this.listQuery.title,
        orderField: this.Sortkey,
        orderType: this.Isace,
        pageNum: this.listQuery.page,
        pageSize: this.listQuery.limit
      }
      this.listLoading = true
      this.$http
        .post('/api/busExamination/queryExaminationPage', para)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            this.list = response.data.result.records
            this.total = response.data.result.total
            if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
              this.listQuery.page = response.data.result.pages
              this.getList()
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.listLoading = false
        })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total
      //   this.listLoading = false
      // })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
